#include "dns.h"

void dns_callback(void *context, const char *name,
		const unsigned char *addr, size_t addrlen)
{
	char 				ip_str[50], *p;
	int 				i;
	global_t			*global;

	global = (global_t *)context;

	if (addrlen == 0) {
		printf("No idea about [%s]\n", name);
	} else {
		//把addr转化成ip字符串
		for (i = 0, p = ip_str; i < addrlen; i++) {
			if (addr[i] > 99) {
				*p++ = addr[i]/100 + 48;
			}
			if (addr[i] > 9) {
				*p++ = addr[i]%100/10 + 48;
			}
			*p++ = addr[i]%10 + 48;
			*p++ = '.';
		}
		*(p-1) = '\0';
		//debug("host = %s\n", name);
		//debug("ip = %s\n", ip_str);

		//把host和ip加入host_table
		ht_insert(global->host_table, name, ip_str);
	}
}

void *query_thread(void *arg)
{
	global_t		*global;
	struct timeval	tv = {3, 0};

	global = (global_t *)arg;

	FD_ZERO(&global->dns_set);
	FD_SET(dns_get_fd(global->dns), &global->dns_set);
	for (;;) {
		if (select(dns_get_fd(global->dns)+1,
					&global->dns_set, NULL, NULL, &tv) > 0) {
			dns_poll(global, global->dns);
		} else {
			sleep(1);
		}
	}

	return (void *)0;
}
